package com.heima.schedule.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author xiaoxiaode
 * @date 2021/10/4 17:25
 **/

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {


    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private CacheService cacheService;


    /*
     *添加延时任务
     */
    public long addTask(Task task) {

        // 添加任务到数据库中
        boolean isSuccess =addTaskToDb(task);

        if(isSuccess){
            // 添加任务到redis中
            addtaskToCache(task);
        }
        return task.getTaskId();
    }


    /*
    * 把任务添加到redis中
    * */
    private void addtaskToCache(Task task) {

        String key=task.getTaskType()+"_"+task.getPriority();

        // 获取5分钟后的时间 毫秒值
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long nextTime = calendar.getTimeInMillis();

        // 如果任务的执行时间小于等于当前时间 存入list中
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key,JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= nextTime){
        // 如果任务的执行时间大于当前时间 && 小于等于预设时间(例如5分钟) 存入zset中
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }

    }

    /*
    *添加任务到数据库中
    * */
    private boolean addTaskToDb(Task task) {

        boolean flag=false;

        try {
            // 保存任务表
            Taskinfo taskinfo=new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            task.setTaskId(taskinfo.getTaskId());

            // 保存任务日志数据
            TaskinfoLogs taskinfoLogs=new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag=true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return flag;
    }


    /*
    *
    * 取消任务
    * */
    public boolean canceTask(long taskId) {

        boolean flag=false;

        // 删除任务,更新任务日志
        Task task=updateDb(taskId,ScheduleConstants.CANCELLED);

        // 删除redis的数据
        if(task!=null){
            removeTaskFromCache(task);
            flag=true;
        }
        return flag;
    }


    /*
    *
    * 删除redis中的数据
    * */
    private void removeTaskFromCache(Task task) {

        String key=task.getTaskType()+"_"+task.getPriority();

        if(task.getExecuteTime() <=System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));
        }
    }


    /*
    * 删除任务,更新任务日志
    * */
    private Task updateDb(long taskId, int status) {
        Task task= null;
        try {
            // 删除任务
            taskinfoMapper.deleteById(taskId);

            // 更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            log.error("task cache error,taskId="+taskId);
        }
        return  task;
    }

    /*
    *
    * 按照类型和优先级拉取任务
    * */
    public Task poll(int type, int priority) {

        Task task=null;

        try {
            String key=type+"_"+priority;
            // 从redis中拉取数据
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if(StringUtils.isNotBlank(task_json)){
                task = JSON.parseObject(task_json, Task.class);
                // 修改数据库信息
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("poll task error");
        }

        return task;
    }

    /*
    *
    * 未来数据定时刷新
    * */
    @Scheduled(cron="0 */1 * * * ?")
    public void refresh(){

        String token=cacheService.tryLock("FUTURE_TASK_SYNC",1000*30);

        if(StringUtils.isNotBlank(token)){
            log.info("未来数据定时刷新-------定时任务");

            // 获取所有未来数据的集合key
            Set<String> keys = cacheService.scan(ScheduleConstants.FUTURE + "*");

            for (String key : keys) {

                // 获取当前数据的key topic
                String topicKey = ScheduleConstants.TOPIC + key.split(ScheduleConstants.FUTURE)[1];

                // 按照key积分值查询符合条件的数据
                Set<String> tasks = cacheService.zRangeByScore(key, 0, System.currentTimeMillis());

                // 同步数据x
                if(!tasks.isEmpty()){
                    cacheService.refreshWithPipeline(key,topicKey,tasks);
                    log.info("成功将"+key+"刷新到"+topicKey);
                }
            }
        }
    }

    /*
    * 数据库任务定时同步到redis
    *
    * */
    // 服务启动的时候就自动同步
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData() {

        // 清理缓存中的数据 list -- zset
        clearCache();

        // 查询符合条件的任务 (小于未来5分钟的数据)
        // 获取5分钟后的时间 毫秒值
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));

        // 把任务添加到redis
        if(taskinfoList!=null && taskinfoList.size()>0){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task=new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addtaskToCache(task);
            }
        }

        log.info("数据库的任务同步到了redis");
    }

    /*
    *
    * 清理缓存中的数据
    * */
    private void clearCache() {

        Set<String> topicKey = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> future = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKey);
        cacheService.delete(future);
    }
}
